﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using ABCNet.Configuration;
using ABCNet.Controllers;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.StaticFiles;
using Microsoft.Extensions.Options;

namespace ABCNet.Web.Host.Controllers
{
    public class UploadFilesController : ABCNetControllerBase
    {
        private readonly IHostingEnvironment _hostingEnvironment;
        public readonly ABCSettings _ABCSettings;
        public UploadFilesController(IHostingEnvironment hostingEnvironment,
            IOptions<ABCSettings> settings)
        {
            _hostingEnvironment = hostingEnvironment;
            _ABCSettings = settings.Value;
        }

        [HttpPost("UploadFiles")]
        public async Task<IActionResult> Post()
        {
            long size = Request.Form.Files.Sum(f => f.Length);

            var basePath = _ABCSettings.UploadFilePath;

            // full path to file in temp location
            // var filePath = Path.GetTempFileName();
            var month = Abp.Timing.Clock.Now.ToString("yyyyMM");
            var saveDirPath = Path.Combine(basePath, month);
            //var webRootPath = $"{_hostingEnvironment.WebRootPath}{serverPath}";
            if (!Directory.Exists(saveDirPath))
            {
                Directory.CreateDirectory(saveDirPath);
            }
            string webPath = "";
            foreach (var formFile in Request.Form.Files)
            {
                if (formFile.Length > 0)
                {
                    var newFileName = $"{Guid.NewGuid()}{Path.GetExtension(formFile.FileName)}";
                    var filePath = Path.Combine(saveDirPath, newFileName);
                    webPath = Path.Combine("UploadFiles/DownLoad",Path.Combine(month, newFileName)).Replace('\\','/');
                    using (var stream = new FileStream(filePath, FileMode.Create))
                    {
                        await formFile.CopyToAsync(stream);
                    }
                }
            }

            return Ok(new { count = Request.Form.Files.Count, size, webPath });
        }

        /// <summary>
        /// 文件流的方式输出        
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Route("UploadFiles/DownLoad/{month}/{file}")]
        public IActionResult DownLoad(string month, string file)
        {
            var basePath = _ABCSettings.UploadFilePath;
            var filePath = Path.Combine(Path.Combine(basePath, month), file);
            var stream = System.IO.File.OpenRead(filePath);
            string fileExt = Path.GetExtension(file);
            //获取文件的ContentType
            var provider = new FileExtensionContentTypeProvider();
            var memi = provider.Mappings[fileExt];
            return File(stream, memi, Path.GetFileName(filePath));
        }

    }
}